﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.WeiBo.WebAPI;
using G.Navigate;
using G.WeiBo.WebAPI.Response;
using G.WeiBo.WebAPI.Request;
using G.Net.Oauth;
using System.Text.RegularExpressions;

namespace G.WeiBo
{
    public partial class MainPage : GBasePage
    {
        //OAuthSina oAuth = new OAuthSina();
        DefaultClient client = new DefaultClient();
        // Constructor
        public MainPage()
        {
            InitializeComponent();

        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            var list = this.NavigationService.BackStack.ToArray();
            foreach (var item in list)
            {
                this.NavigationService.RemoveBackEntry();
            }
            string authorize_url = string.Format("{0}?client_id={1}&response_type={2}&redirect_uri={3}&scope=read,write", Oauth2Config.Request_Authorize_Url, Oauth2Config.ClientID, Oauth2Config.Authorize_ResponseType, HttpUtility.UrlEncode(Oauth2Config.RedirectUri));
            web.Navigate(new Uri(authorize_url));
            
            //OauthConfiger.AccessToken = OAuthAccessToken.Load("sina_token");
            //if (OauthConfiger.AccessToken == null)
            //{
            //    client.Login((c) =>
            //    {
            //        if (c != null)
            //        {
            //            OAuthAccessToken.Save("sina_token", c);
            //            NavigateToIndex();
            //        }
            //    }, "dagehaoshuang@163.com", "ghwghw");
            //}
            //else
            //{
            //    NavigateToIndex();
            //}
        }

        private void NavigateToIndex()
        {
            this.NavigationService.Navigate(new Uri("/View/Index.xaml", UriKind.Relative));
        }


        private void btnLogin_Click(object sender, EventArgs e)
        {

            //G.Net.Oauth.Oauth2Valid.Valid("sina", (c =>
            //{
               
            //}));

            //return;
            //this.Focus();
            //progressbar.Visibility = System.Windows.Visibility.Visible;
            //client.Login((c) =>
            //{
            //    if (c != null)
            //    {
            //        OauthConfiger.AccessToken = c;
            //        OAuthAccessToken.Save(APPConfig.SaveTokenName, c);
            //        this.Dispatcher.BeginInvoke(() =>
            //        {
            //            progressbar.Visibility = System.Windows.Visibility.Collapsed;
            //            NavigateToIndex();
            //        });
                
            //    }
            //    else
            //    {
            //        this.Dispatcher.BeginInvoke(() =>
            //          {
            //              if (!Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            //              {
            //                  MessageBox.Show("网络未连接！");
            //              }
            //              else
            //              {
            //                  MessageBox.Show("用户名或密码错误！");
            //              }
            //              progressbar.Visibility = System.Windows.Visibility.Collapsed;
            //          });
            //    }
            //}, txtUserName.Text, txtPassword.Password);
        }

        private void web_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri.OriginalString.StartsWith(Oauth2Config.RedirectUri))
            {
                string code = e.Uri.Query;
                string pa = "code=(.+?)$";
                var match = Regex.Match(code, pa, RegexOptions.IgnoreCase);
                if (!match.Success)
                    throw new Exception("检索code失败！");
                code = match.Groups[1].Value;
                G.Net.Oauth.Oauth2Valid.Valid(APIConfig.AppName, code, (a) =>
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        this.NavigationService.Navigate(new Uri("/View/Index.xaml", UriKind.Relative));
                    });
                });
                e.Cancel = true;
            }
        }
    }
}